<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
        <img class="the_img" v-if="!this.avatar" src="../../assets/images/avatar.jpg" alt="" />
        <img class="the_img" v-else :src="this.avatar" alt="">

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="iptRef"
          @change="onFileChange"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="uploadFn"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateAvatarAPI } from '@/api'
import { mapGetters } from 'vuex'
import { requestUrl } from '../../utils/request'
export default {
  name: 'UserAvatar',
  computed: {
    ...mapGetters(['username', 'user_pic'])
  },
  data () {
    return {
      avatar: '' // 保存图片连接
    }
  },
  mounted() {
    this.avatar = requestUrl + this.user_pic
  },
  methods: {
    // 选择图片->点击事件->让选择框出现
    chooseImg () {
      // 模拟点击行为
      this.$refs.iptRef.click()
    },
    // 在选择框中选择图片后触发的改变事件
    onFileChange (e) {
      // 获取用户选择的文件列表（伪数组）
      const files = e.target.files
      if (files.length === 0) {
        // 没有选择图片
        this.avatar = ''
      } else {
        // 选择了图片
        console.log(files[0])
        // 使用URL.createObjURL()来转换文件变成图片地址(纯前端本地)
        this.avatar = URL.createObjectURL(files[0])
        this.avatarData = files[0]
      }
    },
    // 上传头像
    async uploadFn () {
      const formData = new FormData()
      formData.append('avatar', this.avatarData)
      formData.append('username', this.username)
      let res = await updateAvatarAPI(formData)
      res = res.data
      console.log(res)
      if (res.code !== 0) return this.$message.error(res.$message)
      // 更新头像成功
      this.$message.success(res.message)
      // 更新vuex的值
      this.$store.dispatch('getUserInfoActions', res.url)
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img {
  width: 350px;
  height: 350px;
}
</style>
